/*
 * WorxRow.java
 *
 * Created Apr 29, 2006
 * David Connell
 * Copyright (c) 2005 Synergy Systems, Inc
 */
package org.puresilk.afx.data;

import java.util.*;

import org.puresilk.afx.SilkAfxException;
import org.puresilk.afx.web.*;

/**
 * A row of data from a WorxResultSet.  contains
 * basics for dealing with disconnected result
 * set.
 */
public class SilkAfxRow {
	private Map<String,Object> data = null;

	/**
	 * Constructor
	 */
	public SilkAfxRow() {
		data = new HashMap<String,Object>();
	}
	
	public void put(String k,Object v) {
		data.put(k,v);
	}
	
	public Object get(String k) {
		return data.get(k);
	}
	
	/**
	 * Get list of fields in set.
	 * @return
	 */
	public Vector<String> getFields() {
		return (Vector<String>)data.keySet();
	}
	/**
	 * Retrieve an int from the row
	 * 
	 * @param k
	 * @return
	 * @throws SilkAfxException
	 */
	public int getInt(String k) throws SilkAfxException {
		int rv = -1;
		
		try {
			Integer val = (Integer)fetchField(k);
			rv = val.intValue();
		}
		catch(SilkAfxException we) {
			// rethrow not found 
			throw we;
		}
		catch(Exception e) {
			// Cast exceptions
			throw new SilkAfxException("Invalid Integer type");
		}
		
		// return result
		return rv;
	}
	
	public double getDouble(String k) throws SilkAfxException {
		double rv = -1;
		
		try {
			Double val = (Double)fetchField(k);
			rv = val.doubleValue();
		}
		catch(SilkAfxException we) {
			// rethrow not found 
			throw we;
		}
		catch(Exception e) {
			// Cast exceptions
			throw new SilkAfxException("Invalid Integer type");
		}
		
		// return result
		return rv;
	}
	
	/**
	 * Retrieve a String value from the row.
	 */
	public String getString(String k) throws SilkAfxException {
		String rv = null;
		try {
			rv = fetchField(k).toString();
		}
		catch(SilkAfxException we) {
			// rethrow 
			throw we;
		}
		catch(Exception e){
			throw new SilkAfxException("Invalid String format");
		}
		
		return rv;
	}
	
	public Date getDate(String k) throws SilkAfxException {
		Date rv = null;
		try {
			rv = (Date)fetchField(k);
		}
		catch(SilkAfxException we) {
			// rethrow 
			throw we;
		}
		catch(Exception e){
			throw new SilkAfxException("Invalid Date Format");
		}
		
		return rv;
	}
	
	public Integer getInteger(String k) throws SilkAfxException {
		Integer rv = null;
		try {
			rv = (Integer)fetchField(k);
		}
		catch(SilkAfxException we) {
			// rethrow 
			throw we;
		}
		catch(Exception e){
			throw new SilkAfxException("Invalid Date Format");
		}
		
		return rv;
	}
	
	public Object getObject(String k) throws SilkAfxException {
		return fetchField(k);
	}
	
	/**
	 * Internal data fetcher.
	 * 
	 * @param k
	 * @return
	 * @throws SilkAfxException
	 */
	private Object fetchField(String k) throws SilkAfxException{
		Object rv = null;
		
		// test for field in row
		if(data.containsKey(k))
			rv = data.get(k);
		else
			throw new SilkAfxException ("Field not found: " + k);
		
		// send back findings
		return rv;
	}
}
